<template>
    <div class="contanier">
      <div class="contanier-title">考试管理</div>
      <search-form>
        <template v-slot:formLeft>
          <el-form :inline="true" :model="userFormLine" class="demo-form-inline">
            <el-row>
              <el-col :span="8">
                <div class="grid-content bg-purple">
                  <el-form-item label="考试名称" label-width="100px">
                    <el-input v-model="userFormLine.fullName" placeholder="请输入"></el-input>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="grid-content bg-purple">
                  <el-form-item label="考试类型" label-width="80px">
                    <el-select v-model="userFormLine.categoryId" placeholder="请选择">
                      <el-option label="理论考试" value="1"></el-option>
                      <el-option label="技能考试" value="2"></el-option>
                      <el-option label="自测" value="3"></el-option>
                      <el-option label="仅考试" value="4"></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="grid-content bg-purple">
                  <el-form-item label="开放权限" label-width="80px">
                    <el-select v-model="userFormLine.scopeRoleId" placeholder="请选择">
                      <el-option v-for="(item, index) in examScopeOptions" :key="index" :id="item.id"
                       :label="item.fullName" :value="item.id"></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-col>
              <!-- <el-col :span="8">
                <div class="grid-content bg-purple">
                  <el-form-item label="状态" label-width="80px">
                    <el-select v-model="userFormLine.status" placeholder="请选择">
                      <el-option label="草稿" value="1"></el-option>
                      <el-option label="已发布" value="2"></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-col> -->
              <el-col :span="12">
                <div class="grid-content bg-purple">
                  <el-form-item label="开始时间" label-width="100px">
                    <el-date-picker
                      v-model="userFormLine.startTime"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      value-format="timestamp">
                      <!-- value-format="yyyy-MM-dd" -->
                    </el-date-picker>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
          </el-form>
        </template>
        <template v-slot:formRight>
          <div class="formRight-btn">
            <el-button icon="el-icon-refresh" class="overPosBtn" @click="resetForm">重 置</el-button>
            <el-button type="primary" @click="onSubmit" icon="el-icon-search" class="set-col-btn">查 询</el-button>
          </div>
        </template>
      </search-form>
      <div>
        <search-table>
          <template v-slot:daochu>
            <div class="set-table-right">
              <el-button icon="el-icon-my-add" @click="addTest">新增考试</el-button>
              <el-button icon="el-icon-my-message" @click="handleExport" :loading="exporting">导 出</el-button>
            </div>
          </template>
          <template v-slot:biaoge>
            <template>
              <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%"
                @selection-change="handleSelectionChange" class="table-top" :header-cell-style="{
                  backgroundColor: '#f5f7fa',
                  color: '#606266',
                }">
                <el-table-column type="index" label="序号" width="50" align="center">
                </el-table-column>
                <el-table-column prop="fullName" label="考试名称" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="categoryId" label="考试类型" align="center" width="100">
                  <template slot-scope="scope">
                    <template v-if="scope.row.categoryId == 1">
                      理论考试
                    </template>
                    <template v-if="scope.row.categoryId == 2">
                      技能考试
                    </template>
                    <template v-if="scope.row.categoryId == 3">
                      自测
                    </template>
                    <template v-if="scope.row.categoryId == 4">
                      仅考试
                    </template>
                  </template>
                </el-table-column>
                <el-table-column prop="examPaperId" label="试卷名称" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="startDatetime" label="开始时间" width="160">
                  <template slot-scope="scope">
                    {{ scope.row.startDatetime || '--' }}
                  </template>
                </el-table-column>
                <el-table-column prop="endDatetime" label="截止时间" width="160">
                  <template slot-scope="scope">
                    {{ scope.row.endDatetime || '--' }}
                  </template>
                </el-table-column>
                <el-table-column prop="scopeRoleNames" label="开放权限" show-overflow-tooltip>
                  <template slot-scope="scope">
                    {{ scope.row.scopeRoleNames ? scope.row.scopeRoleNames : '--' }}
                  </template>
                </el-table-column>
                <!-- <el-table-column prop="examScope" label="开放权限" show-overflow-tooltip>
                  <template slot-scope="scope">
                    {{ scope.row.examScope === '1' ? '大众用户' : scope.row.examScope === '2' ? '培训考试用户' : '--' }}
                  </template>
                </el-table-column> -->
                <el-table-column prop="creatorUserId" label="创建用户">
                </el-table-column>
                <el-table-column prop="creatorTime" label="创建时间" width="160">
                  <template slot-scope="scope">
                    {{ scope.row.creatorTime || '--' }}
                  </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="300">
                  <template slot-scope="scope">
                    <el-button @click.native.prevent="editRow(scope.$index, tableData)" type="text" icon="el-icon-edit"
                    size="small" class="set-table-btn set-table-btn-col">
                    编辑
                  </el-button>
                  <!-- <el-button @click.native.prevent="setsjsz(scope.$index, tableData)" type="text" icon="el-icon-setting"
                    size="small" class="set-table-btn set-table-btn-col">
                    试卷设置
                  </el-button> -->
                  <el-button @click.native.prevent="deleteRow(scope.$index, tableData)" type="text"
                    class="set-table-btn set-table-btn-col" icon="el-icon-document
                                        " size="small">
                    详情
                  </el-button>
                  <el-button @click.native.prevent="delRow(scope.$index, tableData)" type="text"
                    class="set-table-btn set-table-btn-col2" icon="el-icon-delete" size="small" style="color: #d91515">
                    删除
                  </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </template>
          <template v-slot:fenye>
            <div class="set-table-pg-right">
              <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
              </el-pagination>
            </div>
          </template>
        </search-table>
      </div>
  
      <!-- <el-dialog title="试题类型选择" :visible.sync="showSTLX" width="30%">
        <div class="tip">
          <div class="header">
            <ul class="header-ul">
              <li class="header-li" @click="chooseItem(1)">
                <img src="../../assets/images/xztt.png" alt="" />
                <p>选择题</p>
              </li>
              <li class="header-li" @click="chooseItem(2)">
                <img src="../../assets/images/pdt.png" alt="" />
                <p>判断题</p>
              </li>
              <li class="header-li" @click="chooseItem(3)">
                <img src="../../assets/images/wdt.png" alt="" />
                <p>问答题</p>
              </li>
              <li class="header-li" @click="chooseItem(4)">
                <img src="../../assets/images/tkt.png" alt="" />
                <p>填空题</p>
              </li>
            </ul>
          </div>
        </div>
      </el-dialog> -->
  
      <el-dialog title="提示" :visible.sync="showTest" width="30%">
        <div class="tip">
          <div class="header">
            <div class="dia-txt">是否确认删除？</div>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showTest = false">取消</el-button>
          <el-button type="primary" @click="confirmDelete">确认</el-button>
        </span>
      </el-dialog>
      <!-- <pdt :show="showPDT" @closeDrawer="closeDrawer"></pdt>
      <tkt :show="showTKT" @closeDrawer="closeDrawertkt"></tkt>
      <xzt :show="showXZT" @closeDrawer="closeDrawerxZt"></xzt>
      <wdt :show="showWDT" @closeDrawer="closeDrawerwdt"></wdt> -->
    </div>
  </template>
  <script>
  import request from '@/utils/request'
  import SearchForm from "@/components/search-form";
  import SearchTable from "@/components/search-table";
  import pdt from "./pdt";
  import tkt from "./tkt";
  import xzt from "./xzt";
  import wdt from "./wdt";
  import { getExamList, deleteExam, getExamDetail, Update,deleteA , exportExamExecl } from "./api/exam";
  export default {
    name: "UserManagement",
    components: {
      SearchForm,
      SearchTable,
      pdt,
      tkt,
      xzt,
      wdt,
    },
    data() {
      return {
        exporting: false,
        showTest: false,
        currentRow: null,
        tableData1: [{}],
        sjform: {},
        currentExamId: '',
        showsjsz: false,
        showPDT: false,
        showTKT: false,
        showXZT: false,
        showWDT: false,
        showSTLX: false,
        userFormLine: {
          fullName: "",
          status: "",
          startTime: "",
          orderByColumn: "createTime",
          isAsc: "desc",
          categoryId: '',
          scopeRoleId: '',
        },
        tableData: [],
        multipleSelection: [],
        currentPage: 1,
        pageSize: 10,
        total: 0,
        examScopeOptions: [
          {
            "id": "668834371960045637",
            "fullName": "培训考试用户",
            "enCode": "0004",
            "type": "全局",
            "organizeInfo": null,
            "description": "",
            "enabledMark": 1,
            "creatorTime": 1741598943000,
            "sortCode": 0,
            "roleType": "业务角色"
          },
          {
              "id": "669460031602688197",
              "fullName": "大众用户",
              "enCode": "04",
              "type": "全局",
              "organizeInfo": null,
              "description": "",
              "enabledMark": 1,
              "creatorTime": 1741748112000,
              "sortCode": 0,
              "roleType": "业务角色"
          }
        ]
      };
    },
    created() {
      this.getTableList();
    },
    mounted() {
      // request({
      //   url: `api/permission/Role?n=1743175635&organizeId=0&keyword=&currentPage=1&pageSize=20&sort=desc&sidx=&typeList=ApplicationRole&menuId=07029F61-993A-4A46-BF56-20DE382F4F66`,
      //   method: 'get'
      // })
      // .then(res => {
      //   this.examScopeOptions = res.data.list
      //   console.log(this.examScopeOptions, 1111)
      // })
    },
    methods: {
      async setsjsz(index, row) {
        try {
          const res = await getDetail(row[index].id);
          if (res.code === 200) {
            this.currentExamId = row[index].id;
            // 设置表单数据
            this.sjform = {
              fullName: res.data.fullName || '',
              paperType: res.data.paperType || '1',
              paperrandomVersion: res.data.paperrandomVersion || '1',
              enCode: res.data.categoryId || ''
            };
  
            // 设置分值表格数据
            this.tableData1 = [{
              singleScore: res.data.singleScore || 0,
              multipleScore: res.data.multipleScore || 0,
              judgeScore: res.data.judgeScore || 0,
              fillScore: res.data.fillScore || 0,
              questionScore: res.data.questionScore || 0,
              passScore: res.data.passLine || 0
            }];
  
            this.showsjsz = true;
          } else {
            this.$message.error(res.msg || '获取考试设置失败');
          }
        } catch (error) {
          console.error('获取考试设置失败:', error);
          this.$message.error('获取考试设置失败');
        }
      },
      async saveExamSettings() {
        try {
          // 验证总分是否为100
          const scores = this.tableData1[0];
          const totalScore = Number(scores.singleScore || 0) +
            Number(scores.multipleScore || 0) +
            Number(scores.judgeScore || 0) +
            Number(scores.fillScore || 0) +
            Number(scores.questionScore || 0);
  
          if (totalScore !== 100) {
            this.$message.error('总分必须等于100分');
            return;
          }
  
          // 构建更新参数
          const params = {
            folders: "[\"638100473177446981\"]",
            id: this.currentExamId,
            fullName: this.sjform.fullName,
            paperType: this.sjform.paperType,
            categoryId: this.sjform.enCode,
            paperrandomVersion: this.sjform.paperrandomVersion,
            passLine: this.tableData1[0].passScore,
            myScore: totalScore,
            passScore: this.tableData1[0].passScore,
            singleScore: this.tableData1[0].singleScore,
            multipleScore: this.tableData1[0].multipleScore,
            judgeScore: this.tableData1[0].judgeScore,
            fillScore: this.tableData1[0].fillScore,
            questionScore: this.tableData1[0].questionScore,
            enabledMark: null,
            rules: [],
            questions: [],
            deleteMark: null
          };
  
          const res = await Update(params);
          if (res.code === 200) {
            this.$message.success('保存成功');
            this.showsjsz = false;
            this.getTableList(); // 刷新列表
          } else {
            this.$message.error(res.msg || '保存失败');
          }
        } catch (error) {
          console.error('保存失败:', error);
          this.$message.error('保存失败');
        }
      },
      closeDrawer() {
        this.showPDT = false;
      },
      closeDrawertkt() {
        this.showTKT = false;
      },
      closeDrawerxZt() {
        this.showXZT = false;
      },
      closeDrawerwdt() {
        this.showWDT = false;
      },
      chooseItem(val) {
        switch (val) {
          case 1:
            this.showXZT = true;
            break;
          case 2:
            this.showPDT = true;
            break;
          case 3:
            this.showWDT = true;
            break;
          case 4:
            this.showTKT = true;
            break;
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      handleSizeChange(val) {
        this.pageSize = val;
        this.getTableList();
      },
      handleCurrentChange(val) {
        this.currentPage = val;
        this.getTableList();
      },
      addTest() {
        this.$router.push('/test/examAdd');
      },
      async editRow(index, row) {
        try {
          const res = await getExamDetail(row[index].id);
          if (res.code === 200) {
            const data = res.data;
            
            let aadd = {
              ...data,
              validTime: data.startDatetime && data.endDatetime ? [
                this.formatDateTime(data.startDatetime),
                this.formatDateTime(data.endDatetime)
              ] : [],
              paperName: data.examPaperId,
            }
            console.log(aadd, '----aadd---')
            // return;


            // 导航到新增页面，传递完整数据
            this.$router.push({
              path: "/test/examAdd",
              query: { 
                type: 'edit',
                id: row[index].id,
                formData: JSON.stringify({
                  ...data,
                  validTime: data.startDatetime && data.endDatetime ? [
                    this.formatDateTime(data.startDatetime),
                    this.formatDateTime(data.endDatetime)
                  ] : [],
                  // paperName: data.examPaperId,
                  paperName: row[index].examPaperId
                }),
                scoreData: JSON.stringify({
                  singleScore: data.singleScore || 0,
                  multipleScore: data.multipleScore || 0,
                  judgeScore: data.judgeScore || 0,
                  fillScore: data.fillScore || 0,
                  questionScore: data.questionScore || 0,
                  passScore: data.passLine || 60
                })
              }
            });
          } else {
            this.$message.error(res.msg || '获取考试详情失败');
          }
        } catch (error) {
          console.error('获取考试详情失败:', error);
          this.$message.error('获取考试详情失败');
        }
      },
      async deleteRow(index, row) {
        try {
          const res = await getExamDetail(row[index].id);
          if (res.code === 200) {
            const data = res.data;
            // 导航到新增页面，传递完整数据
            this.$router.push({
              path: "/test/examAdd",
              query: { 
                type: 'detail',
                id: row[index].id,
                formData: JSON.stringify({
                  ...data,
                  validTime: data.startDatetime && data.endDatetime ? [
                    this.formatDateTime(data.startDatetime),
                    this.formatDateTime(data.endDatetime)
                  ] : [],
                  // paperName: data.examPaperId,
                  paperName: row[index].examPaperId
                }),
                scoreData: JSON.stringify({
                  singleScore: data.singleScore || 0,
                  multipleScore: data.multipleScore || 0,
                  judgeScore: data.judgeScore || 0,
                  fillScore: data.fillScore || 0,
                  questionScore: data.questionScore || 0,
                  passScore: data.passLine || 60
                })
              }
            });
          } else {
            this.$message.error(res.msg || '获取考试详情失败');
          }
        } catch (error) {
          console.error('获取考试详情失败:', error);
          this.$message.error('获取考试详情失败');
        }
      },
      delRow(index, row) {
        this.$confirm('此操作将永久删除该考试, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.confirmDelete(row[index].id);
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      async confirmDelete(id) {
        if (!id) {
          this.$message.error('删除失败：未找到考试ID');
          return;
        }
        
        try {
          const res = await deleteA(id);
          if (res.code === 200) {
            this.$message.success('删除成功');
            this.getTableList();
          } else {
            this.$message.error(res.msg || '删除失败');
          }
        } catch (error) {
          console.error('删除失败:', error);
          this.$message.error('删除失败');
        }
      },
      getTableList() {

        const params = {
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          fullName: this.userFormLine.fullName || null,
          status: this.userFormLine.status || null,
          // startTime: this.userFormLine.startTime ? this.userFormLine.startTime[0] : null,
          // endTime: this.userFormLine.startTime ? this.userFormLine.startTime[1] : null,
          startDatetime: this.userFormLine.startTime,
          orderByColumn: this.userFormLine.orderByColumn,
          isAsc: this.userFormLine.isAsc,
          categoryId: this.userFormLine.categoryId,
          scopeRoleId: this.userFormLine.scopeRoleId
        };
  
        // 移除空值参数
        Object.keys(params).forEach(key => {
          if (params[key] === null || params[key] === '') {
            delete params[key];
          }
        });
  
        getExamList(params).then(res => {
          if (res.code == 200) {
            this.tableData = (res.data.list || []).map(item => ({
              id: item.id || '',
              fullName: item.fullName || '--',
              categoryId: item.categoryId,
              examPaperId: item.examPaperId || '--',
              startDatetime: item.startDatetime || '--',
              endDatetime: item.endDatetime || '--',
              examScope: item.examScope || '--',
              creatorUserId: item.creatorUserId || '--',
              creatorTime: item.creatorTime || '--',
              enabledMark: item.enabledMark || '0',
              scopeRoleNames: item.scopeRoleNames || '--',
            }));
            
            const pagination = res.data.pagination || {};
            this.currentPage = pagination.currentPage || 1;
            this.pageSize = pagination.pageSize || 10;
            this.total = pagination.total || 0;
          } else {
            this.$message.error(res.msg || '获取列表失败');
          }
        }).catch(error => {
          console.error('获取列表失败:', error);
          this.$message.error('获取列表失败');
        });
      },
      resetForm() {
        this.userFormLine = {
          fullName: "",
          status: "",
          startTime: "",
          orderByColumn: "createTime",
          isAsc: "desc",
          categoryId: '',
          scopeRoleId: '',
        };
        this.currentPage = 1;
        this.getTableList();
      },
      onSubmit() {
        this.currentPage = 1;
        this.getTableList();
      },
      // 添加状态切换处理方法
      handleStatusChange(row) {
        console.log('状态切换:', row.id, row.zt);
        // TODO: 这里添加状态更新的接口调用
      },
      formatExpiryDate(lastModifyTime) {
        if (!lastModifyTime) return '--';
        try {
          // 将lastModifyTime转换为Date对象
          const modifyDate = new Date(lastModifyTime);
          // 添加10天
          const expiryDate = new Date(modifyDate.getTime() + 10 * 24 * 60 * 60 * 1000);
          // 格式化日期为 YYYY-MM-DD
          return expiryDate.toISOString().split('T')[0];
        } catch (error) {
          return '--';
        }
      },
      async handleExport() {

        let data = {
          ...this.userFormLine,
          currentPage: this.currentPage,
          pageSize: 10000,
        };
        let paras = "selectKey=fullName,categoryId,examPaperId,startDatetime,endDatetime,creatorUserId,creatorTime&dataType=0"
        exportExamExecl(paras,data).then(res => {
          if (res.code === 200) {
            this.jsbos.downloadFile(res.data.url);
          }
        })

        // if (this.exporting) return;
        // try {
        //   this.exporting = true;
          
        //   // 创建一个隐藏的 a 标签用于下载
        //   const link = document.createElement('a');
        //   link.style.display = 'none';
          
        //   // 直接调用导出接口，不带任何参数
        //   const baseUrl = process.env.VUE_APP_BASE_API || '';
        //   link.href = `${baseUrl}/api/exam/export`;
        //   link.download = `考试列表_${new Date().toLocaleDateString()}.xlsx`;
          
        //   document.body.appendChild(link);
        //   link.click();
        //   document.body.removeChild(link);
          
        //   this.$message.success('导出成功');
        // } catch (error) {
        //   console.error('导出失败:', error);
        //   this.$message.error('导出失败');
        // } finally {
        //   this.exporting = false;
        // }
      },
      // 添加复制方法
      copyRow(index, rows) {
        const row = rows[index];
        this.$router.push({ 
          path: "/testAdd/index",
          query: { 
            type: 'copy',
            id: row.id 
          }
        });
      },
      // 添加考试设置方法
      examSettings(index, rows) {
        const row = rows[index];
        this.$router.push({ 
          path: "/test/examSettings",
          query: { 
            id: row.id 
          }
        });
      },
      // 添加更多操作的处理方法
      handleCommand(command, row) {
        switch (command) {
          case 'detail':
            this.deleteRow(this.tableData.indexOf(row), [row]);
            break;
          case 'delete':
            this.delRow(this.tableData.indexOf(row), [row]);
            break;
        }
      },
      // 添加时间格式化方法
      formatDateTime(timestamp) {
        if (!timestamp) return '';
        const date = new Date(timestamp);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      },
    },
  };
  </script>
  <style scoped lang="scss">
  ::v-deep .el-icon-my-message {
    background: url("../../assets/images/dc.png") no-repeat;
    width: 20px;
    height: 20px;
  }
  
  ::v-deep .el-icon-my-message:before {
    content: "替";
    font-size: 20px;
    visibility: hidden;
  }
  
  ::v-deep .el-icon-my-message {
    font-size: 18px;
  }
  
  ::v-deep .el-icon-my-message:before {
    content: "\e611";
  }
  
  ::v-deep .el-icon-my-add {
    background: url("../../assets/images/addPaper.png") no-repeat;
    width: 20px;
    height: 20px;
  }
  
  ::v-deep .el-icon-my-add:before {
    content: "替";
    font-size: 20px;
    visibility: hidden;
  }
  
  ::v-deep .el-icon-my-add {
    font-size: 18px;
  }
  
  ::v-deep .el-icon-my-add:before {
    content: "\e611";
  }
  
  .header-ul {
    list-style: none;
    display: flex;
  
    li {
      width: 115px;
      height: 164px;
      text-align: center;
      background: #f6f8fc;
      margin-left: 12px;
  
      img {
        margin-top: 34px;
      }
  
      p {
        margin-top: 6px;
      }
    }
  }
  
  .sjform-tip {
    width: 100%;
    height: 46px;
    background: #fffbe8;
    border-radius: 4px;
    line-height: 46px;
    color: #ed6a0c;
    box-sizing: border-box;
    padding-left: 16px;
  }
  </style>
  